import React, { useState, useEffect } from 'react';
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom';
import {
  Layout,
  Menu,
  Button,
  Dropdown,
  Avatar,
  Space,
  Breadcrumb,
  Drawer,
  Grid,
  theme,
  Modal,
  Form,
  Input,
  Upload,
  message
} from 'antd';
import { 
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  AppstoreOutlined,
  ProjectOutlined,
  ContactsOutlined,
  SettingOutlined,
  UserOutlined,
  LogoutOutlined,
  GlobalOutlined,
  HomeOutlined,
  TeamOutlined,
  UploadOutlined,
  CameraOutlined,
  ShoppingOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import { useAuthStore } from '../services/store';
import { useConfirm } from '../components/ui/ConfirmDialog';
import { useRouteLoading } from '../hooks/useRouteLoading';


import { APP_CONFIG } from '../constants';
import type { MenuProps } from 'antd';

const { Header, Sider, Content } = Layout;

const AdminLayout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout } = useAuthStore();

  const { token: { colorBgContainer } } = theme.useToken();
  const loading = useRouteLoading();
  
  const [collapsed, setCollapsed] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [profileModalOpen, setProfileModalOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  // 检测屏幕尺寸
  useEffect(() => {
    const checkScreenSize = () => {
      const mobile = window.innerWidth < 768;
      setIsMobile(mobile);
      if (mobile) {
        setCollapsed(true);
      }
    };
    
    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

  // 路由切换时自动返回顶部
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [location.pathname]);

  // 菜单项
  const menuItems: MenuProps['items'] = [
    {
      key: '/cxggad/dashboard',
      icon: <DashboardOutlined />,
      label: <Link to="/cxggad/dashboard">仪表盘</Link>
    },
    {
      key: '/cxggad/products',
      icon: <ShoppingOutlined />,
      label: <Link to="/cxggad/products">产品管理</Link>
    },
    {
      key: '/cxggad/cases',
      icon: <FileTextOutlined />,
      label: <Link to="/cxggad/cases">案例管理</Link>
    },
    {
      key: '/cxggad/system',
      icon: <TeamOutlined />,
      label: <Link to="/cxggad/system">系统管理</Link>
    }
  ];

  // 用户下拉菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
      onClick: () => setProfileModalOpen(true)
    },
    {
      key: 'website',
      icon: <GlobalOutlined />,
      label: <Link to="/" target="_blank">访问网站</Link>
    },
    {
      type: 'divider'
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: () => {
        logout();
        navigate('/login');
      }
    }
  ];

  // 获取当前选中的菜单项
  const selectedKeys = [location.pathname];

  // 生成面包屑
  const getBreadcrumbItems = () => {
    const pathSnippets = location.pathname.split('/').filter(i => i);
    const breadcrumbNameMap: Record<string, string> = {
      cxggad: '管理后台',
      dashboard: '仪表盘',
      products: '产品管理',
      cases: '案例管理',
      system: '系统管理'
    };

    const breadcrumbItems = [
      {
        title: (
          <Link to="/">
            <HomeOutlined />
            <span className="ml-1">首页</span>
          </Link>
        )
      }
    ];

    pathSnippets.forEach((snippet, index) => {
      const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
      const isLast = index === pathSnippets.length - 1;
      
      breadcrumbItems.push({
        title: isLast ? (
          <span>{breadcrumbNameMap[snippet] || snippet}</span>
        ) : (
          <Link to={url}>
            {breadcrumbNameMap[snippet] || snippet}
          </Link>
        )
      });
    });

    return breadcrumbItems;
  };

  const { ConfirmComponent } = useConfirm();

  return (
    <Layout className="h-screen overflow-hidden">
      {/* 桌面端侧边栏 */}
      {!isMobile && (
        <Sider 
          trigger={null} 
          collapsible 
          collapsed={collapsed}
          className="shadow-lg h-full"
          theme="dark"
          style={{ height: '100vh', position: 'fixed', left: 0, top: 0, bottom: 0 }}
        >
          {/* Logo区域 */}
          <div className="h-16 flex items-center justify-center border-b border-gray-700">
            {collapsed ? (
              <img 
                src="/logo.png"
                alt="Logo"
                className="h-8 w-8"
              />
            ) : (
              <div className="flex items-center space-x-2">
                <img 
                  src="/logo.png"
                  alt={APP_CONFIG.siteName}
                  className="h-8 w-auto"
                />
                <span className="text-white font-bold text-lg">
                  管理后台
                </span>
              </div>
            )}
          </div>

          {/* 导航菜单 */}
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={selectedKeys}
            items={menuItems}
            className="border-none"
          />
        </Sider>
      )}

      {/* 移动端抽屉菜单 */}
      <Drawer
        title={
          <div className="flex items-center space-x-2">
            <img 
              src="/logo.png"
              alt={APP_CONFIG.siteName}
              className="h-6 w-auto"
            />
            <span className="font-bold">管理后台</span>
          </div>
        }
        placement="left"
        onClose={() => setMobileMenuOpen(false)}
        open={mobileMenuOpen}
        width={280}
        styles={{ body: { padding: 0 } }}
        className="md:hidden"
      >
        <Menu
          mode="vertical"
          selectedKeys={selectedKeys}
          items={menuItems}
          onClick={() => setMobileMenuOpen(false)}
          className="border-none"
        />
      </Drawer>

      <Layout style={{ marginLeft: !isMobile ? (collapsed ? 80 : 200) : 0 }}>
        {/* 顶部栏 */}
        <Header 
          style={{ 
            padding: '0 24px', 
            background: colorBgContainer,
            borderBottom: '1px solid #f0f0f0',
            position: 'fixed',
            top: 0,
            right: 0,
            left: !isMobile ? (collapsed ? 80 : 200) : 0,
            zIndex: 1000
          }}
          className="flex items-center justify-between shadow-sm"
        >
          {/* 左侧：折叠按钮和面包屑 */}
          <div className="flex items-center space-x-4">
            <Button
              type="text"
              icon={isMobile ? <MenuUnfoldOutlined /> : (collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />)}
              onClick={() => {
                if (isMobile) {
                  setMobileMenuOpen(true);
                } else {
                  setCollapsed(!collapsed);
                }
              }}
              className="text-lg"
            />
            
            <div className="hidden sm:block">
              <Breadcrumb items={getBreadcrumbItems()} />
            </div>
          </div>

          {/* 右侧：用户信息 */}
          <Space size={isMobile ? "middle" : "large"}>
            {/* 用户信息 */}
            <Dropdown 
              menu={{ items: userMenuItems }} 
              placement="bottomRight"
              arrow
            >
              <Space className="cursor-pointer hover:bg-gray-50 px-2 py-1 rounded">
                <Avatar 
                  src={user?.avatar} 
                  icon={<UserOutlined />}
                  size="small"
                >
                  {!user?.avatar && user?.username?.charAt(0).toUpperCase()}
                </Avatar>
                {!isMobile && (
                  <div className="text-right">
                    <div className="text-sm font-medium text-gray-900">
                      {user?.nickname || user?.username}
                    </div>
                    <div className="text-xs text-gray-500">
                      {user?.role === 'admin' ? '管理员' : '游客'}
                    </div>
                  </div>
                )}
              </Space>
            </Dropdown>
          </Space>
        </Header>

        {/* 主要内容区域 */}
        <Content
          style={{
            margin: '0',
            marginTop: '64px',
            height: 'calc(100vh - 64px)',
            background: '#f5f5f5',
            overflow: 'auto'
          }}
        >
          <Outlet />
        </Content>
      </Layout>
      
      {/* 用户资料编辑模态框 */}
      <Modal
        title={
          <div className="flex items-center space-x-2">
            <UserOutlined className="text-blue-500" />
            <span>个人资料</span>
          </div>
        }
        open={profileModalOpen}
        onCancel={() => setProfileModalOpen(false)}
        footer={null}
        width={500}
        destroyOnHidden
      >
        <ProfileEditForm 
          user={user} 
          onClose={() => setProfileModalOpen(false)}
        />
      </Modal>
      

      
      {ConfirmComponent}
    </Layout>
  );
};

// 用户资料编辑表单组件
const ProfileEditForm: React.FC<{
  user: any;
  onClose: () => void;
}> = ({ user, onClose }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState(user?.avatar || '');

  // 初始化表单数据
  useEffect(() => {
    if (user) {
      form.setFieldsValue({
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar
      });
      setAvatarUrl(user.avatar || '');
    }
  }, [user, form]);

  // 头像上传处理
  const handleAvatarChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // 模拟上传成功，实际项目中应该从服务器返回的URL
      const newAvatarUrl = URL.createObjectURL(info.file.originFileObj);
      setAvatarUrl(newAvatarUrl);
      form.setFieldValue('avatar', newAvatarUrl);
      setLoading(false);
      message.success('头像上传成功');
    }
  };

  // 表单提交处理
  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      // 这里应该调用API更新用户信息
      // console.log('更新用户信息:', values);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success('个人资料更新成功');
      onClose();
    } catch (error) {
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const uploadButton = (
    <div className="flex flex-col items-center justify-center w-full h-full">
      {loading ? (
        <div className="text-gray-400">上传中...</div>
      ) : (
        <>
          <CameraOutlined className="text-2xl text-gray-400 mb-2" />
          <div className="text-sm text-gray-500">点击上传头像</div>
        </>
      )}
    </div>
  );

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      className="space-y-4"
    >
      {/* 头像上传 */}
      <div className="text-center">
        <Form.Item
          label="头像"
          name="avatar"
        >
          <div className="flex justify-center">
            <Upload
              name="avatar"
              listType="picture-circle"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={() => false} // 阻止自动上传
              onChange={handleAvatarChange}
            >
              {avatarUrl ? (
                <img 
                  src={avatarUrl} 
                  alt="avatar" 
                  className="w-full h-full object-cover rounded-full" 
                />
              ) : (
                uploadButton
              )}
            </Upload>
          </div>
        </Form.Item>
        <div className="text-xs text-gray-500 mt-2">
          支持 JPG、PNG 格式，文件大小不超过 2MB
        </div>
      </div>

      {/* 用户名（不可修改） */}
      <Form.Item
        label="用户名"
        name="username"
      >
        <Input 
          placeholder="用户名不可修改" 
          prefix={<UserOutlined className="text-gray-400" />}
          disabled
          className="bg-gray-50"
        />
      </Form.Item>

      {/* 昵称 */}
      <Form.Item
        label="昵称"
        name="nickname"
        rules={[
          { required: true, message: '请输入昵称' },
          { min: 2, max: 20, message: '昵称长度为2-20个字符' }
        ]}
      >
        <Input 
          placeholder="请输入昵称" 
          prefix={<UserOutlined className="text-gray-400" />}
        />
      </Form.Item>

      {/* 新密码 */}
      <Form.Item
        label="新密码"
        name="newPassword"
        rules={[
          { min: 6, message: '密码长度至少6个字符' }
        ]}
      >
        <Input.Password 
          placeholder="留空则不修改密码" 
        />
      </Form.Item>

      {/* 确认密码 */}
      <Form.Item
        label="确认密码"
        name="confirmPassword"
        dependencies={['newPassword']}
        rules={[
          ({ getFieldValue }) => ({
            validator(_, value) {
              const newPassword = getFieldValue('newPassword');
              if (!newPassword && !value) {
                return Promise.resolve();
              }
              if (!value) {
                return Promise.reject(new Error('请确认新密码'));
              }
              if (newPassword !== value) {
                return Promise.reject(new Error('两次输入的密码不一致'));
              }
              return Promise.resolve();
            },
          }),
        ]}
      >
        <Input.Password 
          placeholder="请再次输入新密码" 
        />
      </Form.Item>

      {/* 操作按钮 */}
      <div className="flex justify-end space-x-3 pt-4 border-t">
        <Button onClick={onClose}>
          取消
        </Button>
        <Button 
          type="primary" 
          htmlType="submit" 
          loading={loading}
          className="bg-blue-500 hover:bg-blue-600"
        >
          保存修改
        </Button>
      </div>
    </Form>
  );
};

export default AdminLayout;